package com.summer.tools.flowable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.summer.tools.common.enums.ResponseCodeEnum;
import com.summer.tools.common.model.SimplePage;
import com.summer.tools.common.utils.Assert;
import com.summer.tools.common.utils.JsonUtil;
import com.summer.tools.flowable.VO.FieldModel;
import com.summer.tools.flowable.VO.FormModel;
import com.summer.tools.flowable.common.IdGenerator;
import com.summer.tools.flowable.constants.TemplateConstants;
import com.summer.tools.flowable.orm.model.ProcessForm;
import com.summer.tools.flowable.orm.dao.ProcessFormMapper;
import com.summer.tools.flowable.orm.model.ProcessFormField;
import com.summer.tools.flowable.service.IProcessFormFieldService;
import com.summer.tools.flowable.service.IProcessFormService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 表单表 服务实现类
 * </p>
 *
 * @author john.wang
 * @since 2021-08-19
 */
@Service
public class ProcessFormServiceImpl extends ServiceImpl<ProcessFormMapper, ProcessForm> implements IProcessFormService {

    @Resource
    private IProcessFormFieldService fieldService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addForm(FormModel form) {
        Assert.notNull(form.getKey(), ResponseCodeEnum.DATA_NOT_EXISTS, "formKey");

        Assert.notEmpty(form.getFields(), ResponseCodeEnum.DATA_NOT_EXISTS, "form fields");

        // 插入表单数据
        ProcessForm processForm = new ProcessForm()
                .setId(IdGenerator.generateId(TemplateConstants.IdPrefixEnum.FORM))
                .setKey(form.getKey()).setName(form.getName())
                .setContent(JsonUtil.stringify(form));
        processForm.insert();
        // 插入表单字段数据
        this.fieldService.saveBatch(form, processForm.getId());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateForm(FormModel form) {
        Assert.notNull(form.getKey(), ResponseCodeEnum.DATA_NOT_EXISTS, "formKey");

        Assert.notEmpty(form.getFields(), ResponseCodeEnum.DATA_NOT_EXISTS, "form fields");
        ProcessForm processForm = this.getOne(new QueryWrapper<ProcessForm>().eq(ProcessForm.KEY, form.getKey()));

        Assert.notEmpty(processForm, ResponseCodeEnum.DATA_NOT_EXISTS, "form fields");
        processForm.setName(form.getName());
        processForm.updateById();

        // 先删除再插入
        List<String> fieldKeys = form.getFields().stream().map(FieldModel::getId).collect(Collectors.toList());
        this.fieldService.remove(new QueryWrapper<ProcessFormField>()
                .eq(ProcessFormField.FORM_ID, processForm.getId()).in(ProcessFormField.KEY, fieldKeys)
        );

        // 插入表单字段数据
        this.fieldService.saveBatch(form, processForm.getId());

    }

    @Override
    public FormModel getForm(String formKey) {
        ProcessForm processForm = this.getOne(new QueryWrapper<ProcessForm>().eq(ProcessForm.KEY, formKey));
        Assert.notNull(processForm, ResponseCodeEnum.DATA_NOT_EXISTS, "form");
        return JsonUtil.parse(processForm.getContent(), FormModel.class);
    }

    @Override
    public SimplePage<FormModel> list(String name) {

        IPage<ProcessForm> page = this.page(new Page<>(), new QueryWrapper<ProcessForm>()
                .eq(StringUtils.isNotBlank(name), ProcessForm.NAME, name));

        List<FormModel> formModels = new ArrayList<>();
        page.getRecords().forEach(f -> {
            FormModel formModel = JsonUtil.parse(f.getContent(), FormModel.class);
            formModels.add(formModel);
        });
        return new SimplePage<>(page.getTotal(), formModels);
    }

}
